﻿
using System;
using System.Collections.Generic;
using System.Data;

using static Models.Common.EnumDeviceState;
using Microsoft.EntityFrameworkCore;
using GateWayCloodService.Data;
using UtilsORM.MySql_IotGateway;
using UtilsORM;
using UtilsCache;

namespace GateWayCloodService.CloudCenter
{
    public class ServiceCloodDeleteLog
    {
        public void taskRun()
        {
            Task.Run(() =>
            {


                try
                {
                    //服务器重启后，会有连接数超过的报错，这个执行后，可解决 
                    //清空已经缓存的客户端主机信息,重新建立连接
                    string sql = " flush hosts;";
                    MySqlIotGateway.ExecuteCommandAsync(sql);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

                while (true)
                {
                    try
                    {
                        var lockobj = UtilFreeRedis.getLock("ServiceCloodDeleteLog", 1);
                        if (lockobj != null)
                        {

                            if (DateTime.Now.Minute == 30)
                            {
                                Console.WriteLine("数据清理完成");

                                deleteCommandHaddleing();
                                Console.WriteLine("超时数据处理");

                            }

                            //删除锁
                            lockobj.Unlock();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

                    Thread.Sleep(55 * 1000);
                }
            });
        }

        /// <summary>
        /// 网关待办超时，设备无响应
        /// </summary>
        public void deleteCommandHaddleing()
        {
            try
            {
                EFIotGatewayContext ef = new EFIotGatewayContext();
                //超时数据删除
                DateTime dt = DateTime.Now.AddMinutes(-1);
                List<iot_device_command_haddleing> haddleings_timeout = ef.iot_device_command_haddleing.Where(c => c.l_add_time < dt).ToList();
                foreach (iot_device_command_haddleing item in haddleings_timeout)
                {
                    //系统错误
                    new DBIotSystemLogError().addSystemLogErrorForCommand_haddleing(item.l_d_guid, item.l_key, item.l_return_msg, "返回数据值，长度不一致");

                    //设备异常
                    new ServiceCloudDeviceLiveState().setDeviceLiveState(item.l_d_guid, 2, "请求无响应");
                    //  new ServiceCloudDeviceLiveState().setUnResponse(item.l_d_guid, "请求无响应");
                    //删除
                    ef.iot_device_command_haddleing.Remove(item);
                    ef.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }

}
